import ModelInterfaces as mi
import torch
import numpy as np
import epitran
import eng_to_ipa


def get_phonem_converter(language: str):
    if language == 'de':
        phonem_converter = EpitranPhonemConverter(
            epitran.Epitran('deu-Latn'))
    elif language == 'en':
        phonem_converter = EngPhonemConverter()
    elif language == 'zh':
        # Placeholder for Chinese - direct text or a specific converter
        print("Warning: Using EngPhonemConverter for Chinese as a placeholder in get_phonem_converter.")
        phonem_converter = EngPhonemConverter() # Or a specific Chinese converter if available/created
    else:
        raise ValueError(f'Language {language} not implemented for phonem converter')
    return phonem_converter

class EpitranPhonemConverter(mi.ITextToPhonemModel):
    # word_locations_in_samples = None # These attributes seem unrelated to this class
    # audio_transcript = None

    def __init__(self, epitran_model) -> None:
        super().__init__()
        self.epitran_model = epitran_model

    def convertToPhonem(self, sentence: str) -> str:
        if not sentence or sentence == '-': # Handle empty or placeholder strings
            return ""
        phonem_representation = self.epitran_model.transliterate(sentence)
        return phonem_representation


class EngPhonemConverter(mi.ITextToPhonemModel):

    def __init__(self,) -> None:
        super().__init__()

    def convertToPhonem(self, sentence: str) -> str:
        if not sentence or sentence == '-': # Handle empty or placeholder strings
            return ""
        try:
            phonem_representation = eng_to_ipa.convert(sentence)
            phonem_representation = phonem_representation.replace('*','') # Remove syllable stress for cleaner IPA in this context
            phonem_representation = phonem_representation.replace('ˈ','') # Primary stress
            phonem_representation = phonem_representation.replace('ˌ','') # Secondary stress
        except Exception as e:
            print(f"Error converting '{sentence}' to IPA with eng_to_ipa: {e}. Returning original text.")
            phonem_representation = sentence # Fallback to original text if conversion fails
        return phonem_representation 